import React from 'react';
import { observer } from 'mobx-react';
import { Modal, Form, Input, InputNumber, DatePicker, Select, message } from 'antd';
import http from 'libs/http';
import store from './store';
import moment from 'moment';

@observer
class CourseForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      categories: [],
      schools: []
    }
  }

  componentDidMount() {
    // 获取课程类别
    http.get('/api/course/category/')
      .then(res => {
        this.setState({ categories: res });
      })
  }

  handleSubmit = () => {
    this.setState({ loading: true });
    const formData = this.props.form.getFieldsValue();
    formData['id'] = store.record.id;
    
    // 处理日期格式
    if (formData.start_date) {
      formData.start_date = formData.start_date.format('YYYY-MM-DD');
    }
    if (formData.end_date) {
      formData.end_date = formData.end_date.format('YYYY-MM-DD');
    }

    http.post('/api/course/', formData)
      .then(() => {
        message.success('操作成功');
        store.formVisible = false;
        store.fetchRecords()
      }, () => this.setState({ loading: false }))
  };

  render() {
    const info = store.record;
    const { getFieldDecorator } = this.props.form;
    const itemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 }
    };

    return (
      <Modal
        visible
        maskClosable={false}
        title={store.record.id ? '编辑课程' : '新建课程'}
        onCancel={() => store.formVisible = false}
        confirmLoading={this.state.loading}
        onOk={this.handleSubmit}>
        <Form>
          <Form.Item {...itemLayout} required label="课程类别">
            {getFieldDecorator('category_id', {
              initialValue: info['category_id'],
              rules: [{ required: true, message: '请选择课程类别' }]
            })(
              <Select placeholder="请选择">
                {this.state.categories.map(item => (
                  <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                ))}
              </Select>
            )}
          </Form.Item>
          <Form.Item {...itemLayout} required label="课程名称">
            {getFieldDecorator('name', { 
              initialValue: info['name'],
              rules: [{ required: true, message: '请输入课程名称' }]
            })(
              <Input placeholder="请输入课程名称"/>
            )}
          </Form.Item>
          <Form.Item {...itemLayout} required label="课程年份">
            {getFieldDecorator('year', { 
              initialValue: info['year'],
              rules: [{ required: true, message: '请输入课程年份' }]
            })(
              <InputNumber style={{width: '100%'}} placeholder="请输入课程年份" min={2000}/>
            )}
          </Form.Item>
          <Form.Item {...itemLayout} required label="课程价格">
            {getFieldDecorator('price', { 
              initialValue: info['price'],
              rules: [{ required: true, message: '请输入课程价格' }]
            })(
              <InputNumber 
                style={{width: '100%'}} 
                placeholder="请输入课程价格"
                min={0}
                precision={2}
                prefix="¥"
              />
            )}
          </Form.Item>
          <Form.Item {...itemLayout} required label="开始日期">
            {getFieldDecorator('start_date', { 
              initialValue: info['start_date'] ? moment(info['start_date']) : null,
              rules: [{ required: true, message: '请选择开始日期' }]
            })(
              <DatePicker style={{width: '100%'}}/>
            )}
          </Form.Item>
          <Form.Item {...itemLayout} required label="结束日期">
            {getFieldDecorator('end_date', { 
              initialValue: info['end_date'] ? moment(info['end_date']) : null,
              rules: [{ required: true, message: '请选择结束日期' }]
            })(
              <DatePicker style={{width: '100%'}}/>
            )}
          </Form.Item>
          <Form.Item {...itemLayout} required label="课程状态">
            {getFieldDecorator('status', { 
              initialValue: info['status'] || 'pending',
              rules: [{ required: true, message: '请选择课程状态' }]
            })(
              <Select>
                <Select.Option value="pending">未开始</Select.Option>
                <Select.Option value="in_progress">进行中</Select.Option>
                <Select.Option value="finished">已结束</Select.Option>
              </Select>
            )}
          </Form.Item>
        </Form>
      </Modal>
    )
  }
}

export default Form.create()(CourseForm)
